package com.sp.intercepted;

import com.alibaba.fastjson.JSONObject;
import com.sp.constant.EmployeeMessageConstant;
import com.sp.model.entity.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义权限不足处理器
 *
 * @author tong
 */
@Component
public class RequestAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 当访问接口没有权限时，自定义的返回结果
     *
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().println(JSONObject.toJSON(Result.error(EmployeeMessageConstant.EMPLOYEE_NOT_LIMITATION, 401)));
        response.getWriter().flush();
    }

}
